<template>
  <div class="logistics-price-list">
    <el-button type="primary" @click="handleAdd">新增价格配置</el-button>
    
    <el-form :inline="true" :model="queryForm" style="margin: 10px 0;">
      <el-form-item label="公司名称">
        <el-input v-model="queryForm.companyName" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="物流类型" style="width: 200px;">
        <el-select v-model="queryForm.category" placeholder="请选择类型">
          <el-option label="全部" value="" />
          <el-option label="同城" value="1" />
          <el-option label="同省" value="2" />
          <el-option label="跨省" value="3" />
          <el-option label="经济区互寄" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%; margin-top: 10px;">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="company_name" label="所属公司" width="200" />
      <el-table-column prop="category" label="类型" width="120">
        <template #default="scope">
          <span v-if="scope.row.category === 1">同城</span>
          <span v-if="scope.row.category === 2">同省</span>
          <span v-if="scope.row.category === 3">跨省</span>
          <span v-if="scope.row.category === 4">经济区互寄</span>
        </template>
      </el-table-column>
      <el-table-column prop="cube_price" label="每立方费用(分)" width="150" />
      <el-table-column prop="kilogram_price" label="每千克费用(分)" width="150" />
      <el-table-column prop="trans_kilometer_price" label="每千米费用" width="150" />
      <el-table-column prop="is_del" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.is_del == 1" type="success">有效</el-tag>
          <el-tag v-else type="danger">无效</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="form" label-width="150px">
        <el-form-item label="所属公司" prop="logisticsCompanyId" :rules="{ required: true, message: '请选择公司', trigger: 'change' }">
          <el-select v-model="form.logisticsCompanyId" placeholder="请选择物流公司">
            <el-option 
              v-for="company in companyList" 
              :key="company.id" 
              :label="company.companyName" 
              :value="company.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物流类型" prop="category" :rules="{ required: true, message: '请选择类型', trigger: 'change' }">
          <el-select v-model="form.category">
            <el-option label="同城" value="1" />
            <el-option label="同省" value="2" />
            <el-option label="跨省" value="3" />
            <el-option label="经济区互寄" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="每立方费用(分)" prop="cubePrice" :rules="{ required: true, message: '请输入费用', trigger: 'blur' }">
          <el-input v-model.number="form.cubePrice" />
        </el-form-item>
        <el-form-item label="每千克费用(分)" prop="kilogramPrice" :rules="{ required: true, message: '请输入费用', trigger: 'blur' }">
          <el-input v-model.number="form.kilogramPrice" />
        </el-form-item>
        <el-form-item label="每千米运输费用" prop="transKilometerPrice" :rules="{ required: true, message: '请输入费用', trigger: 'blur' }">
          <el-input v-model.number="form.transKilometerPrice" />
        </el-form-item>
        <el-form-item label="状态" prop="isDel">
          <el-select v-model="form.isDel">
            <el-option label="有效" value="1" />
            <el-option label="无效" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getPriceWithCompany, addPrice, updatePrice, deletePrice } from '@/api/logistics'
import { getCompanyList } from '@/api/logistics'
import { ElMessage } from 'element-plus'

const tableData = ref([])
const companyList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增价格配置')
const queryForm = reactive({
  companyName: '',
  category: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const form = reactive({
  id: null,
  cubePrice: 0,
  kilogramPrice: 0,
  transKilometerPrice: 0,
  category: 1,
  logisticsCompanyId: null,
  isDel: 1
})


// 获取价格列表（包含公司信息）
const getList = async () => {
  const params = {
    ...queryForm,
    page: currentPage.value,
    size: pageSize.value
  }
  
  const res = await getPriceWithCompany(params)
  tableData.value = res.data.records.map(item => ({
    ...item,
    companyName: item.company_name,
    cubePrice: item.cube_price,
    kilogramPrice: item.kilogram_price,
    transKilometerPrice: item.trans_kilometer_price,
    logisticsCompanyId: item.logistics_company_id,
    isDel: item.is_del
  }))
  total.value = res.data.total
}

// 获取所有公司列表（用于下拉选择）
const getCompanies = async () => {
  const res = await getCompanyList({ page: 1, size: 100 })
  companyList.value = res.data.records
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增价格配置'
  Object.assign(form, {
    id: null,
    cubePrice: 0,
    kilogramPrice: 0,
    transKilometerPrice: 0,
    category: null,
    logisticsCompanyId: null,
    isDel: null
  })
  dialogVisible.value = true
}

// 编辑
// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑价格配置'
  Object.assign(form, {
    id: row.id,
    cubePrice: row.cube_price,
    kilogramPrice: row.kilogram_price,
    transKilometerPrice: row.trans_kilometer_price,
    category: row.category,
    logisticsCompanyId: row.logistics_company_id,
    isDel: row.is_del
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    if (form.id) {
      await updatePrice(form)
      ElMessage.success('修改成功')
    } else {
      await addPrice(form)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await deletePrice(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 重置查询
const resetQuery = () => {
  queryForm.companyName = ''
  queryForm.category = ''
  currentPage.value = 1
  getList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
  getCompanies()
})
</script>